package fun.stgoder.dev.listener.sdk.dh;

import cn.hutool.core.thread.ThreadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class DhSDKCache {
    private static Logger logger = LoggerFactory.getLogger(DhSDKCache.class);
    private static Map<String, DhSDKWrapper> sdkMap = new HashMap<>();

    private static Thread timer = new Thread(() -> {
        while (true) {
            sdkMap.forEach((ip, sdk) -> {
                if (sdk != null && !sdk.isInitSuccess()) {
                    try {
                        logger.info("reload sdk: " + ip);
                        boolean ret = sdk.login();
                        if (!ret)
                            throw new Exception("sdk login err");

                        ret = sdk.realLoadPicture(0);
                        if (!ret)
                            throw new Exception("sdk realLoadPicture err");

                        sdk.setInitSuccess(true);
                    } catch (Exception e) {
                        logger.error("reload sdk", e);
                    }
                }
            });
            ThreadUtil.sleep(10, TimeUnit.MINUTES);
        }
    });

    static {
        timer.start();
    }

    public static DhSDKWrapper initAndPut(String ip, int port, String username, String password) {
        DhSDKWrapper sdk = new DhSDKWrapper(ip, port, username, password);
        try {

            boolean ret = sdk.init();
            if (!ret)
                throw new Exception("sdk init err");
            ret = sdk.login();
            if (!ret)
                throw new Exception("sdk login err");

            ret = sdk.realLoadPicture(0);
            if (!ret)
                throw new Exception("sdk realLoadPicture err");
            sdk.setInitSuccess(true);
            logger.info("init sdk success: " + ip);
        } catch (Exception e) {
            logger.error("init sdk", e);
        }

        sdkMap.put(ip, sdk);
        return sdk;
    }

    public static void cleanAndRemove(String ip) {
        try {
            DhSDKWrapper sdk = get(ip);
            if (sdk != null) {
                sdk.logout();
                sdk.stopRealLoadPicture();
                sdk.cleanup();
            }
            sdkMap.remove(ip);
        } catch (Exception e) {
            logger.error("clean sdk", e);
        }
    }

    public static DhSDKWrapper get(String ip) {
        return sdkMap.get(ip);
    }
}
